package com.ctu.app.utils;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

import android.os.Environment;
import android.util.Log;
import de.mindpipe.android.logging.log4j.LogCatAppender;
import de.mindpipe.android.logging.log4j.LogConfigurator;

public class ConfigureLog4J {
	private static Logger runLogger;
	private static Logger exceptionLogger;
	static SimpleDateFormat formatFileName = new SimpleDateFormat("yyyy_MM_dd");
	static String usedFileName;// 正在使用的文件名
	private static final String TAG = "ConfigureLog4J";
	private static boolean DEBUG = true;
	static LogConfigurator logConfigurator;
	static String filePath;

	private static void createNewFile() {

	}

	/**
	 * 配置logger
	 * 
	 * @return
	 */
	public static Logger configure() {
		logConfigurator = new LogConfigurator();
		filePath = Environment.getExternalStorageDirectory() + File.separator
				+ "AutoDial" + File.separator + "logs" + File.separator;

		usedFileName = formatFileName.format(new Date());

		logConfigurator.setFileName(filePath + usedFileName + ".log");
		logConfigurator.setRootLevel(Level.DEBUG);
		logConfigurator.setLevel("org.apache", Level.ERROR);
		logConfigurator.setFilePattern("%d %-5p [%c{2}]-[%L] %m%n");
		logConfigurator.setMaxFileSize(1024 * 1024 * 5);//
		logConfigurator.setImmediateFlush(true);
		logConfigurator.configure();
		runLogger = Logger.getLogger("AutoDialRunLog");// 获取到记录器
		return runLogger;
	}

	private static boolean compareDate() {
		String newDate = formatFileName.format(new Date());// 新时间
		String oldDate = usedFileName;// 旧的时间
		if (DEBUG) {
			Log.d(TAG, "newDate: " + newDate + "," + "oldDate: " + oldDate);
		}
		DateFormat df = new SimpleDateFormat("yyyy_MM_dd");
		try {

			Date current = df.parse(newDate);
			Date old = df.parse(oldDate);

			if (current.getTime() > old.getTime()) {
				if (DEBUG) {
					Log.d(TAG, "重新创建log文件:" + newDate);

				}
				usedFileName = newDate;
				return true;
			} else {// 同一天
				if (DEBUG) {
					Log.d(TAG, "使用原log文件:" + oldDate);// 使用之前的线程
				}
				return false;
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return false;
	}

}
